package vip.liux.backend.infrastructure.textTemplate;

import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import vip.liux.backend.infrastructure.textTemplate.spi.TemplateRenderingEngine;

import java.util.Locale;
import java.util.Map;
import java.util.ServiceLoader;

public class EngineTemplateRenderer implements TemplateRenderer {

    public static final String DEFAULT_RENDER_ENGINE = "thymeleaf";

    @Override
    public String render(String template, @Nullable Map<String, Object> model, @Nullable Locale locale, @Nullable Map<String, Object> globalContext) {

        TemplateDefinition templateDefinition = new TemplateDefinition(template, null);

        String renderEngine = templateDefinition.getRenderEngine();
        if (StringUtils.isBlank(renderEngine)) {
            renderEngine = DEFAULT_RENDER_ENGINE;
        }

        TemplateRenderingEngine renderingEngine = null;

        for (TemplateRenderingEngine engine : ServiceLoader.load(TemplateRenderingEngine.class)) {
            if (engine.supports(renderEngine)) {
                renderingEngine = engine;
                break;
            }
        }

        if (renderingEngine == null) {
            throw new IllegalArgumentException("There is no rendering engine found with template name: " + template);
        }

        return renderingEngine.render(template, model, locale, globalContext);
    }
}
